﻿using System;
using System.ComponentModel;
using System.Windows;
using Microsoft.Phone.Controls;

namespace FluentAppBar
{
    public static class AppBar
    {
        public static readonly DependencyProperty FluentAppBarProperty = DependencyProperty.RegisterAttached(
            "FluentAppBar", typeof(IDisposable), typeof(AppBar), new PropertyMetadata(default(IDisposable)));

        public static void SetFluentAppBar(PhoneApplicationPage element, IDisposable value)
        {
            element.SetValue(FluentAppBarProperty, value);
        }

        public static IDisposable GetFluentAppBar(PhoneApplicationPage element)
        {
            return (IDisposable)element.GetValue(FluentAppBarProperty);
        }

        public static IFluentAppBar<T> Setup<T>(PhoneApplicationPage page)
            where T : INotifyPropertyChanged
        {
            var appBar = page.ApplicationBar;
            if (appBar == null)
            {
                throw new InvalidOperationException("There is no application bar");
            }

            var viewModel = (T)page.DataContext;
            if (viewModel == null)
            {
                throw new InvalidOperationException("There is no view model attached");
            }

            var currentFluentAppbar = GetFluentAppBar(page);
            if (currentFluentAppbar != null)
                currentFluentAppbar.Dispose();

            var newFluentAppBar = new FluentAppBar<T>(appBar, viewModel);
            SetFluentAppBar(page, newFluentAppBar);

            return newFluentAppBar;
        }
    }
}
